﻿#region Copyright Info

// 
// Majesty of Omega - The next evolution of macro management space strategy
// 
// Copyright 2007-2009 André Claaßen
// 
// This file is protected by the terms and conditions of the
// Microsoft Community License (Ms-CL 1.1), a copy of which should
// have been distributed along with this software. If not,
// you may find the license information at the following URL:
// 
// http://www.microsoft.com/resources/sharedsource/licensingbasics/communitylicense.mspx

#endregion

#region

using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Threading;
using DesignByContract;

#endregion

namespace Majesty_of_Omega.GUI.Animation
{
    /// <summary>
    /// This class handels a navigation from a page to a page
    /// </summary>
    public static class AnimatedNavigationService
    {
        /// <summary>
        /// Navigation source
        /// </summary>
        private static Page _fromPage;

        /// <summary>
        /// Navigation target
        /// </summary>
        private static Page _toPage;

        /// <summary>
        /// Initialize a new instance of <see cref="AnimatedNavigationService"/> class.
        /// This class handles a animated transition between to page.
        /// The from page, with the unload animation, should implement
        /// the <see cref="ITransitionAnimation"/> Interface.
        /// </summary>
        /// <param name="navigationService">The navigation service.</param>
        /// <param name="toPage">To page.</param>
        public static void Navigate(NavigationService navigationService, Page toPage)
        {
            Ensure.IsNotNull(navigationService);
            _fromPage = (Page) navigationService.Content;
            _toPage = toPage;
            var animation = _fromPage as ITransitionAnimation;
            if (animation != null)
            {
                var dispatcherTimer = new DispatcherTimer {Interval = animation.Duration};
                dispatcherTimer.Tick += delegate
                                            {
                                                dispatcherTimer.Stop();
                                                if (_fromPage.NavigationService != null)
                                                    _fromPage.NavigationService.Navigate(_toPage);
                                            };
                dispatcherTimer.Start();
                animation.StartUnloadAnimation();
            }
            else
            {
                if (_fromPage.NavigationService != null)
                    _fromPage.NavigationService.Navigate(toPage);
            }
        }
    }
}